package com.jtmg.glorykingsnews.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jtmg.glorykingsnews.domain.TbGoods;
import com.jtmg.glorykingsnews.vo.commom.MsgVo;
import com.jtmg.glorykingsnews.vo.goods.GoodsAddVo;
import com.jtmg.glorykingsnews.vo.goods.GoodsQuery;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import com.jtmg.glorykingsnews.mapper.TbGoodsMapper;
import com.jtmg.glorykingsnews.service.TbGoodsService;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class TbGoodsServiceImpl implements TbGoodsService{

    @Resource
    private TbGoodsMapper tbGoodsMapper;

    @Override
    public PageInfo<TbGoods> queryGoodsByName(GoodsQuery query) {
        Example example = new Example(TbGoods.class);
        Example.Criteria criteria =example.createCriteria().andEqualTo("deleted",0);
        String category = query.getgName();
        if (category != null && !"".equals(category)){
            System.out.println(query.getgName());
            criteria.andLike("category","%"+category+"%");
        }
        PageHelper.startPage(query.getPage(), query.getLimit());
        return new PageInfo<>(tbGoodsMapper.selectByExample(example));
    }

    @Override
    public MsgVo<TbGoods> queryGoodsByParentId(GoodsQuery query) {
        Example example = new Example(TbGoods.class);
        example.createCriteria().andEqualTo("deleted",0)
                .andEqualTo("parentId",query.getParentId());
        PageHelper.startPage(query.getPage(), query.getLimit());
        List<TbGoods> goodsList = tbGoodsMapper.selectByExample(example);
        if (goodsList == null){
            TbGoods goods = tbGoodsMapper.selectByPrimaryKey(query.getParentId());
            return new MsgVo<TbGoods>("200","查找商品类型成功",goods);
        }
        return new MsgVo<TbGoods>("200","查找商品类型成功",goodsList);
    }

    @Override
    public MsgVo addGoods(GoodsAddVo vo) {
        Example example = new Example(TbGoods.class);
        example.createCriteria().andEqualTo("deleted",0)
                .andEqualTo("category",vo.getgName());
        List<TbGoods> list = tbGoodsMapper.selectByExample(example);
        if (list != null){
            return new MsgVo("201","该商品已存在");
        }
        TbGoods goods = new TbGoods();
        goods.setCategory(vo.getgName());
        goods.setParentId(vo.getParentId());
        goods.setDeleted(0);
        tbGoodsMapper.insert(goods);
        return new MsgVo("200","商品新增成功");
    }

    @Override
    public MsgVo deleteGoods(int id) {
        Example example = new Example(TbGoods.class);
        example.createCriteria().andEqualTo("id",id);
        TbGoods goods = new TbGoods();
        goods.setDeleted(1);
        tbGoodsMapper.updateByExample(goods,example);
        return new MsgVo("200","商品删除成功");    }
}
